package com.yobol.jgrowth.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

public class Command {
	
	private BufferedReader outBufferedReader = null;
	private BufferedReader errorBufferedReader = null;
	public void exec(String cmd) {
		try {
			Runtime.getRuntime().exec(cmd);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public Map<String,String> exec(String path,String name,String code,String cmd) {
		Map<String,String> map = new HashMap<>();
		StringBuilder out = new StringBuilder();
		StringBuilder error = new StringBuilder();
		try {
			createFile(path, name, code);
			Process process = Runtime.getRuntime().exec(cmd);
			outBufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
			errorBufferedReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
			String line = null;
			while((line = outBufferedReader.readLine()) != null) {
				out.append(line + "\n");
			}
			while((line = errorBufferedReader.readLine()) != null) {
				error.append(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(outBufferedReader != null) {
					outBufferedReader.close();
				}
				if(errorBufferedReader != null) {
					errorBufferedReader.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		map.put("out", out.toString());
		map.put("error", error.toString());
		return map;
	}
	
	private void createFile(String path,String name,String code) {
		File file = new File(path + name);
		FileOutputStream fileOutputStream = null;
		try {
			if(!file.exists()) {
				file.createNewFile();
				//write file content
				fileOutputStream = new FileOutputStream(file,true);
				StringBuffer buffer = new StringBuffer(code);
				fileOutputStream.write(buffer.toString().getBytes());
			}
		}catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				if(fileOutputStream != null) {
					fileOutputStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
